<template>
  <div class="dashboard-editor-container">
    <el-row>
      <div class="filter-container">

        <el-select class="filter-item" v-model="listQuery.user_id" clearable filterable remote reserve-keyword placeholder="登录名/姓名/手机号" @change="changeMethod" :remote-method="remoteMethod" :loading="loading">
          <el-option v-for="item in selectData" :key="item.id" :label='item.name + "/" + item.username + "/" + item.phoneNumber' :value="item.id">
          </el-option>
        </el-select>

        <el-button class="filter-item" rigth style="margin-rigth: 10px;" @click="handleCreate" type="primary" icon="el-icon-plus">下单</el-button>
      </div>
      <el-table highlight-current-row height="700" :data="list" style="width: 100%;" show-summary>
        <el-table-column type="expand">

          <template slot-scope="props">

            <el-form label-position="left" inline class="demo-table-expand" v-for='p in props.row.orderDetail' :key="p.id">
              <el-form-item label="商品名称">
                <span>{{ p.good.name }}</span>
              </el-form-item>
              <el-form-item label="数量">
                <span>{{ p.num }}</span>
              </el-form-item>
              <el-form-item label="原价">
                <span>{{ p.totalMoney }}</span>
              </el-form-item>
              <el-form-item label="折扣">
                <span>{{ p.discount * 10 + '折' }}</span>
              </el-form-item>
              <el-form-item label="折后">
                <span>{{ p.totalDiscountMoney }}</span>
              </el-form-item>
              <el-form-item label="实收">
                <span>{{ p.totalActualCharge }}</span>
              </el-form-item>
              <el-form-item label="积分">
                <span>{{ p.total_integral }}</span>
              </el-form-item>
            </el-form>

          </template>

        </el-table-column>
        <el-table-column label="订单号" min-width="120" align="center">
          <template slot-scope="scope">
            {{scope.row.orderId}}
          </template>
        </el-table-column>
        <el-table-column label="姓名" min-width="120" align="center">
          <template slot-scope="scope">
            {{scope.row.user.name}}
          </template>
        </el-table-column>
        <el-table-column label="原价" min-width="120" align="center" prop="totalMoney">
          <template slot-scope="scope">
            {{scope.row.totalMoney | currency}}
          </template>
        </el-table-column>
        <el-table-column label="折扣" min-width="120" align="center">
          <template slot-scope="scope">
            {{scope.row.discount | discountFilter}}
          </template>
        </el-table-column>
        <el-table-column label="折后" min-width="120" align="center" prop="totalDiscountMoney">
          <template slot-scope="scope">
            {{scope.row.totalDiscountMoney | currency}}
          </template>
        </el-table-column>

        <el-table-column label="实收" min-width="120" align="center" prop="totalActualCharge">
          <template slot-scope="scope">
            {{scope.row.totalActualCharge | currency}}
          </template>

        </el-table-column>
        <el-table-column label="积分" min-width="120" align="center" prop="totalActualCharge">
          <template slot-scope="scope">
            {{scope.row.total_integral }}
          </template>

        </el-table-column>
        <el-table-column label="创建时间" min-width="180" align="center">
          <template slot-scope="scope">
            {{scope.row.createdAt | moment('YYYY-MM-DD hh:mm:ss')}}
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <!-- <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="listQuery.page" :page-sizes="[10,20,30,50]" :page-size="listQuery.limit" layout="total, sizes, prev, pager, next, jumper" :total="total"> -->
        <el-pagination background small @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="listQuery.page" :page-size="listQuery.limit" layout="prev, pager, next" :total="total">
        </el-pagination>
      </div>

      <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :before-close="handleClose">
        <el-popover ref="addRecordsPopover" placement="right" width="400" trigger="click">
          <el-form :inline="true" class="demo-form-inline">
            <el-form-item :label="$t('userInfo.table.records')">
              <el-input v-model="addReocrd"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleAddReocrd">添加</el-button>
            </el-form-item>
          </el-form>
        </el-popover>
        <el-form :rules="rules" ref="dataForm" :model="temp" label-position="right" label-width="70px" style='width: 400px; margin-left:50px;'>
          <el-form-item label="选择用户" prop="user">
            <el-select v-model="temp.user" clearable filterable remote reserve-keyword placeholder="登录名/姓名/手机号" @change="changeUser" :remote-method="remoteMethodAdd" :loading="loading">
              <el-option v-for="item in selectDataAdd" :key="item.id" :label='item.name + "/" + item.username + "/" + item.phoneNumber' :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('userInfo.table.records')" prop="records">
            <el-select class="filter-item" multiple default-first-option v-model="temp.records" placeholder="请选择">
              <el-option v-for="item in records" :key="item.id" :label="item.display" :value="item.id">
              </el-option>
            </el-select>

            <el-tooltip content="添加病史" placement="top">
              <el-button type="primary" icon="el-icon-plus" v-popover:addRecordsPopover></el-button>
            </el-tooltip>
          </el-form-item>
          <el-form-item label="消费类型" prop="type">
            <el-select v-model="temp.type" clearable placeholder="请选择">
              <el-option key='0' value="0" label="赠送"></el-option>
              <el-option key='1' value="1" label="预存款"></el-option>
              <el-option key='2' value="2" label="积分"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="备注" prop="note">
            <el-input type="textarea" v-model="temp.note"></el-input>
          </el-form-item>
          <el-form-item prop="orderDetail">
            <el-select v-model="selectGood" placeholder="选择商品" :loading="loading">
              <el-option v-for="(item, index) in goods" :key="item.id" :label='item.name' :value="index">
              </el-option>
            </el-select>
            <el-button @click="handleAddGood">增加商品</el-button>
          </el-form-item>
        </el-form>

        <el-row>
          <el-table :data="addGoods" highlight-current-row style="width: 100%;">
            <el-table-column label="商品" min-width="120" align="center" prop="name">
            </el-table-column>
            <el-table-column label="数量" min-width="210" align="center">
              <template slot-scope="scope">
                <el-input-number controls-position="right" v-model="scope.row.num" @change="changeNum" :min="1" :step="1" label="数量"></el-input-number>
              </template>
            </el-table-column>
            <el-table-column label="单价" min-width="80" align="center" prop="price">
            </el-table-column>
            <el-table-column label="原价" min-width="80" align="center">
              <template slot-scope="scope">
                <el-tag>{{scope.row.price * scope.row.num}}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="折扣" min-width="80" align="center" prop="discount">
            </el-table-column>
            <el-table-column label="折后" min-width="80" align="center">
              <template slot-scope="scope">
                <el-tag>{{scope.row.price * scope.row.num * scope.row.discount}}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="实收" min-width="120" align="center">
              <template slot-scope="scope">
                <el-input type="text" v-model="scope.row.actualCharge"></el-input>
              </template>
            </el-table-column>
          </el-table>
        </el-row>

        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">{{$t('table.cancel')}}</el-button>
          <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">{{$t('table.confirm')}}</el-button>
          <el-button v-else type="primary" @click="updateData">{{$t('table.confirm')}}</el-button>
        </div>
      </el-dialog>

      <!-- <el-dialog :title="预存款管理" :visible.sync="preDialogFormVisible" :before-close="handleClose">
    </el-dialog> -->
    </el-row>
  </div>
</template>

<script>
import { scanUser } from '@/api/user'
import { createOrder, getOrderList, getOrderForUser } from '@/api/order'
import { getRecordList, addRecord } from '@/api/record'
import { getGoodList } from '@/api/good'
export default {
  data() {
    return {
      selectGood: null,
      discount: null,
      goods: [],
      addGoods: [],
      addReocrd: '',
      records: [],
      selectData: [],
      selectDataAdd: [],
      loading: false,
      list: null,
      total: null,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 10,
        user_id: ''
      },
      temp: {
        note: '',
        type: '1',
        user: null,
        records: [],
        orderDetail: []
      },
      detail: {
        good: 0,
        num: 0,
        totalActualCharge: 0
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      rules: {},
      preDialogFormVisible: false
    }
  },
  filters: {
    discountFilter(discount) {
      return discount * 10 + ' 折'
    },
    currency(num, fString = '￥', cNum = 2) {
      return fString + Number(num).toFixed(cNum)
    }
  },
  created() {
    this.fetchData()
    getRecordList().then(response => {
      var data = response.data
      this.records = data
    })
  },
  methods: {
    fetchData() {
      if (this.listQuery.user_id) {
        getOrderForUser(this.listQuery.page, this.listQuery.limit, this.listQuery.user_id).then(response => {
          var data = response.data
          this.list = data.results
          this.total = data.count
        })
      } else {
        getOrderList(this.listQuery.page, this.listQuery.limit).then(response => {
          var data = response.data
          this.list = data.results
          this.total = data.count
        })
      }
    },
    handleFilter() {
      this.fetchData()
    },

    handleCreatePre(row) {
      this.preDialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleSizeChange(val) {
      this.listQuery.limit = val
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.fetchData()
    },
    resetTemp() {
      this.temp = {
        note: '',
        type: '1',
        user: null,
        records: [],
        orderDetail: []
      }
      this.addGoods = []
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done()
        })
        .catch(_ => { })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const d = []
          this.addGoods.forEach(function(value, index, arr) {
            d.push({
              good: arr[index]['id'],
              num: arr[index]['num'],
              totalActualCharge: arr[index]['actualCharge']
            })
          })
          this.temp.orderDetail = d
          createOrder(this.temp).then(response => {
            const data = response.data
            if (data.flag) this.list.unshift(this.temp)
            this.dialogFormVisible = !data.flag
            this.$notify({
              title: '预存款/积分操作',
              message: data.flag ? '追加成功' : data.errorMsg,
              type: data.flag ? 'success' : 'error',
              duration: 5000
            })
            this.fetchData()
          })
        }
      })
    },
    remoteMethod(query) {
      if (query !== '') {
        this.loading = true
        scanUser(query).then(response => {
          this.selectData = response.data.results
          this.loading = false
        })
      } else {
        this.selectData = []
        this.loading = false
      }
    },
    remoteMethodAdd(query) {
      if (query !== '') {
        this.loading = true
        scanUser(query).then(response => {
          this.selectDataAdd = response.data.results
          this.loading = false
        })
      } else {
        this.selectData = []
        this.loading = false
      }
    },
    changeMethod(value) {
      this.listQuery.page = 1
      this.fetchData()
    },
    handleAddReocrd() {
      const tempData = { 'display': this.addReocrd }
      addRecord(tempData).then(response => {
        const data = response.data
        this.$notify({
          title: '添加成功',
          message: data.flag ? '添加病史成功' : data.errorMsg,
          type: data.flag ? 'success' : 'error',
          duration: 5000
        })
        if (data.flag) this.addReocrd = ''
        getRecordList().then(response => {
          var data = response.data
          this.records = data
        })
      })
    },
    handleAddGood() {
      const data = this.goods[this.selectGood]
      const addData = {
        id: data.id,
        name: data.name,
        isDiscount: data.isDiscount,
        discount: data.discount,
        price: data.price,
        num: 1,
        actualCharge: data.price * 1 * data.discount
      }
      this.addGoods.push(addData)
    },
    changeGood(value) {
      const index = this.goods.findIndex(function(row, index, arr) {
        return row.id === value
      })
      console.log(index)
    },
    changeNum(value) {
      this.addGoods.forEach(function(value, index, arr) {
        arr[index]['actualCharge'] = arr[index]['price'] * arr[index]['num'] * arr[index]['discount']
      })
      console.log('asd')
    },
    changeUser(value) {
      const data = this.selectDataAdd.find((i) => {
        if (i.id === value) {
          getGoodList(i.id).then(response => {
            var data = response.data
            this.goods = data.data
          })
          return i
        }
      })
      if (data.discount < 1) this.discount = data.discount
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.dashboard-editor-container {
    padding: 32px;
    background-color: rgb(240, 242, 245);
    .chart-wrapper {
        background: #fff;
        padding: 16px 16px 0;
        margin-bottom: 32px;
    }
}
.demo-table-expand {
    font-size: 0;
}
.demo-table-expand label {
    width: 90px;
    color: #99a9bf;
}
.demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 10%;
}
</style>
